package bsc.war.handler;

import bsc.ejb.entity.Comparator;
import bsc.ejb.entity.DimensionMember;
import bsc.ejb.entity.DimensionalCut;
import bsc.ejb.entity.Person;
import bsc.ejb.entity.Pointer;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.service.ScoreCardUtils;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author Memo
 */
public class PointerTemplate extends AbstractController {

    public PointerTemplate() {
    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");

            processRequestInternal(request, response, delegate);

        } catch (Exception e) {
            logger.error("Catched exception", e);
        }
        return null;
    }

    public static void processRequestInternal(HttpServletRequest request,
            HttpServletResponse response, DelegateBSC delegate) {


        try {

            response.setContentType("application/vnd.ms-excel"); //Tipo de fichero.
            response.setHeader("Content-Disposition", "attachment;filename=\"template.xls\"");

            //Find Person
            HttpSession session = request.getSession();

            Person person = (Person)session.getAttribute("person");


            //Person person = delegate.findPerson(3L);

            //Find the scorecard
            /*Long idPointerDimensionalCut = Long.parseLong(request.getParameter("scoreCard"));
            DimensionalCut pointerDimensionalCut = delegate.findDimensionalCut(idPointerDimensionalCut);*/

            //Pointer of the scorecard
            Long idPointer = Long.parseLong(request.getParameter("scoreCard"));
            Pointer pointer = (Pointer)delegate.findScoreCard(idPointer);

            //Find the cuts of the pointer
            List<DimensionalCut> dimensionalCuts = delegate.findDimensionalCut((Pointer) pointer);

            //List of dimensionalCuts of the person
            List<DimensionalCut> dimensionalCutsPerson = new ArrayList<DimensionalCut>();

            //Check the responsable of the dimensionalCuts - Pointer
            for (DimensionalCut dimensionalCut : dimensionalCuts) {
                Person responsable = dimensionalCut.getResponsible();
                if(person.equals(responsable) || person.getProfile()== person.getProfile().DATA_MANAGER){
                    dimensionalCutsPerson.add(dimensionalCut);
                }
            }

           
            //Members of the cut
            Map<DimensionalCut, List<DimensionMember>> cutMembers = new HashMap<DimensionalCut, List<DimensionMember>>();
            //Members of members boolean
            Map<DimensionalCut, Map<DimensionMember, Boolean>> cutMembersSons = new HashMap<DimensionalCut, Map<DimensionMember, Boolean>>();

            //Members Strng of the Cut
            Map<DimensionalCut, String> cutMembersString = new HashMap<DimensionalCut, String>();

            for (DimensionalCut dimensionalCut : dimensionalCutsPerson) {
                List<DimensionMember> dimensionMembers = delegate.findDimensionMember(dimensionalCut);

                cutMembers.put(dimensionalCut, dimensionMembers);
                cutMembersString.put(dimensionalCut, ScoreCardUtils.createMembersString(dimensionMembers));
                //check if members have sons
                cutMembersSons.put(dimensionalCut, ScoreCardUtils.reviewMembersSons(dimensionMembers, delegate));

            }
            
            //Comparator of the pointer
            List<Comparator> comparators = delegate.findComparator(pointer);

            


            HSSFWorkbook wb = new HSSFWorkbook();

            //Create a sheet for each comparator

            for (Comparator comparator : comparators) {
                HSSFSheet sheetComparator = wb.createSheet("" + comparator.getDescription());

                //POINTER ROW
                HSSFRow rowPointer = sheetComparator.createRow(0);
                rowPointer.createCell(0).setCellValue("Indicador");
                //ID
                rowPointer.createCell(1).setCellValue(pointer.getIdScoreCard());
                //Name
                rowPointer.createCell(2).setCellValue(pointer.getName());
                //Period
                rowPointer.createCell(3).setCellValue("" + pointer.getSettings().getFrecuency());
                //Unit
                rowPointer.createCell(5).setCellValue("Unidad de Medida");
                rowPointer.createCell(5).setCellValue(pointer.getUnit());

                //COMPARATOR

                HSSFRow rowComparator = sheetComparator.createRow(1);
                rowComparator.createCell(0).setCellValue("Comparador");
                //ID
                rowComparator.createCell(1).setCellValue(comparator.getIdComparator());
                //Name
                rowComparator.createCell(2).setCellValue(comparator.getDescription());

                //Cuts Row
                HSSFRow rowCuts = sheetComparator.createRow(3);
                rowCuts.createCell(0).setCellValue("Fecha (dd/mm/aaaa)");
                //System.out.println("El numero de cortes es: " + dimensionalCuts.size());
                for (int i = 0; i < dimensionalCutsPerson.size(); i++) {
                    DimensionalCut dimensionalCut = dimensionalCutsPerson.get(i);
                    //List<DimensionMember> dimensionMembers = cutMembers.get(dimensionalCut);
                    String cutString = cutMembersString.get(dimensionalCut);

                    //rowCuts.createCell(i+1).setCellValue(dimensionalCut.getIdDimensionalCut() + "-" + cutString);
                    rowCuts.createCell(i+1).setCellValue(dimensionalCut.getIdScoreCard() + "-" + cutString);
                }

                //SE AGREGAN LOS DATOS EXISTENTES
                //Se obtiene la fecha de inicio del indicador
                Date startDate = pointer.getSettings().getRegisterDate();
                //Se obtiene la fecha final
                Date endDate = ScoreCardUtils.getLastDate();
                //Se crean los periodos
                List<Date> listDates = ScoreCardUtils.generateDatesRange(startDate, endDate, pointer);
                List<Date> finalListDates = new ArrayList<Date>();

                for (Date date : listDates) {
                    if(!ScoreCardUtils.hasData(delegate, pointer, comparator, date)){
                       finalListDates.add(date);
                        
                    }
                }
                
                int countDates=4;
                for (Date date : finalListDates) {
                    HSSFRow rowDate = sheetComparator.createRow(countDates);
                    HSSFCellStyle cellStyle = wb.createCellStyle();
                    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
                    HSSFCell cellaData = rowDate.createCell(0);
                    cellaData.setCellStyle(cellStyle);
                    cellaData.setCellValue(date);
                    countDates++;
                }
                

            }

            OutputStream output = response.getOutputStream();


            wb.write(output);
            output.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
